package com.flainsky.nirvanaplayer.globe;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;

import com.flainsky.nirvanaplayer.coder.MovieObjectSerializable;
import com.flainsky.nirvanaplayer.lib.objects.Movie;

public class HistroyController {
	
	private List<Movie> list;
	private final String HISTROY_SP_NAME = "histroy_saves";
	private final String HISTROY_LIST = "histroy_list"; 
	
	private static HistroyController instance;
	private static Context mContext;
	
	public static HistroyController getInstance() {
		if(instance!=null){
			return instance;
		}
		else{
			makeInstance(mContext);
			return instance;
		}
	}
	public static synchronized void makeInstance(Context context){
		mContext = context;
		if(instance==null){
			instance=new HistroyController();
		}
	}
	private HistroyController(){
		load();
		if(list == null)
		{
			list = new ArrayList<Movie>();
		}
	}
	
	public void addHistroy(Movie info)
	{
		if(list == null)return;
		list.add(0, info);
	}
	
	public List<Movie> getHistroy()
	{
		return list;
	}
	
	public void save()
	{
		if(list == null)return;
		if(list.size()==0)
		{
			//清除记录数据
			SharedPreferences serviceInfo = mContext.getSharedPreferences(HISTROY_SP_NAME, 0);
			serviceInfo.edit().clear().commit();
		}
		else
		{
			//写入记录
			SharedPreferences serviceInfo = mContext.getSharedPreferences(HISTROY_SP_NAME, 0);
			String datas = MovieObjectSerializable.Encode(list);
			serviceInfo.edit().putString(HISTROY_LIST, datas).commit();
		}
	}
	
	public boolean clearItem(Movie info)
	{
		return list.remove(info);
	}
	
	public void load()
	{
		SharedPreferences serviceInfo = mContext.getSharedPreferences(HISTROY_SP_NAME, 0);
		String datas = serviceInfo.getString(HISTROY_LIST, "");
		if(datas.equals(""))
		{
			return;
		}
		list = MovieObjectSerializable.MovieDecode(datas);
	}
}
